package com.swap.business.constants;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.swap.business.domain.SwapDevice;
import com.swap.business.domain.SwapDeviceInfo;
import com.swap.business.dto.SnmpMessageDTO;
import com.swap.business.service.DeviceDataAcquisitionService;
import com.swap.business.service.DeviceInfoService;
import com.swap.common.utils.DateUtils;
import com.swap.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class ConsumerListener {

    private static final Logger logger = LoggerFactory.getLogger(ConsumerListener.class);

    @Autowired
    private DeviceDataAcquisitionService acquisitionService;

    @Autowired
    private DeviceInfoService infoService;

    /**
     * 监听队列消息
     *
     * @param message 接收到的消息
     */
//    @RabbitListener(queuesToDeclare = @Queue(value = "swap_queue"))
    @RabbitListener(queues = "swap_queue")
    public void handle(String message) {
        SwapDevice device = JSON.parseObject(message, SwapDevice.class);
        logger.info("队列监听交换机设备信息接收成功，接收时间:{},消息内容为：{}", DateUtils.getTime(), message);
        try {
            // 基本信息
            SnmpMessageDTO dto = new SnmpMessageDTO();
            dto.setIp(device.getDeviceIp());
            dto.setCommunity(device.getCommunityRead());
            dto.setVersion(device.getVersion());
            acquisitionService.queryGetAllDeviceInfo(dto, device); // 这里不再阻塞等待结果
        } catch (Exception e) {
            logger.warn("Unexpected exception while processing message for device: {}", device.getDeviceName());
        }
    }

    //    @RabbitListener(queuesToDeclare = @Queue(value = "swap_queue"))
    @RabbitListener(queues = "swap_remove_queue")
    public void removeHandle(String message) throws JsonProcessingException {
        SwapDeviceInfo info = JSON.parseObject(message, SwapDeviceInfo.class);
        try {
            if (StringUtils.isNotEmpty(info.getId())) {
                infoService.removeById(info.getId());
            }
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
    }
}
